<template>
  <div class="app-container">
    <el-form 
      :model="queryParams" 
      ref="queryForm" 
      size="small" 
      :inline="true" 
      v-show="showSearch" 
      label-width="68px"
    >
      <el-form-item label="学号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="互动类型" prop="interactionType">
        <el-select 
          v-model="queryParams.interactionType" 
          placeholder="请选择互动类型" 
          clearable
        >
          <el-option label="提问" value="1" />
          <el-option label="回答" value="2" />
          <el-option label="讨论" value="3" />
          <el-option label="投票" value="4" />
          <el-option label="签到" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="互动时间" prop="interactionTime">
        <el-date-picker 
          clearable
          v-model="queryParams.interactionTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择互动时间"
        />
      </el-form-item>
      <el-form-item label="获得的积分奖励" prop="scoreRewarded">
        <el-input
          v-model="queryParams.scoreRewarded"
          placeholder="请输入获得的积分奖励"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select 
          v-model="queryParams.status" 
          placeholder="请选择状态" 
          clearable
        >
          <el-option label="有效" value="1" />
          <el-option label="无效" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:interaction:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:interaction:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:interaction:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:interaction:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="interactionList" 
      @selection-change="handleSelectionChange"
      border
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" width="80" />
      <el-table-column label="学号" align="center" prop="userId" width="100" />
      <el-table-column label="课程ID" align="center" prop="courseId" width="100" />
      <el-table-column label="课程名称" align="center" prop="courseName" width="180" />
      <el-table-column label="互动类型" align="center" prop="interactionType" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.interactionType === 1">提问</el-tag>
          <el-tag v-else-if="scope.row.interactionType === 2" type="success">回答</el-tag>
          <el-tag v-else-if="scope.row.interactionType === 3" type="info">讨论</el-tag>
          <el-tag v-else-if="scope.row.interactionType === 4" type="warning">投票</el-tag>
          <el-tag v-else-if="scope.row.interactionType === 5" type="primary">签到</el-tag>
          <el-tag v-else type="danger">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="互动内容" align="center" prop="interactionContent" />
      <el-table-column label="互动时间" align="center" prop="interactionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.interactionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分奖励" align="center" prop="scoreRewarded" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">有效</el-tag>
          <el-tag v-else type="danger">无效</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:interaction:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:interaction:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生课堂互动记录对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="500px" 
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form 
        ref="form" 
        :model="form" 
        :rules="rules" 
        label-width="80px"
        size="small"
      >
        <el-form-item label="学号" prop="userId">
          <el-input 
            v-model="form.userId" 
            placeholder="请输入学号" 
            clearable
          />
        </el-form-item>
        <el-form-item label="课程ID" prop="courseId">
          <el-input 
            v-model="form.courseId" 
            placeholder="请输入课程ID" 
            clearable
          />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input 
            v-model="form.courseName" 
            placeholder="请输入课程名称" 
            clearable
          />
        </el-form-item>
        <!-- 新增：互动类型下拉框（必填） -->
        <el-form-item label="互动类型" prop="interactionType">
          <el-select 
            v-model="form.interactionType" 
            placeholder="请选择互动类型" 
            clearable
          >
            <el-option label="提问" value="1" />
            <el-option label="回答" value="2" />
            <el-option label="讨论" value="3" />
            <el-option label="投票" value="4" />
            <el-option label="签到" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="互动内容" prop="interactionContent">
          <editor v-model="form.interactionContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="互动时间" prop="interactionTime">
          <el-date-picker 
            clearable
            v-model="form.interactionTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择互动时间"
          />
        </el-form-item>
        <el-form-item label="积分奖励" prop="scoreRewarded">
          <el-input 
            v-model="form.scoreRewarded" 
            placeholder="请输入获得的积分奖励" 
            clearable
            type="number"
            min="0"
          />
        </el-form-item>
        <!-- 新增：状态下拉框（必填，避免后续报错） -->
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="form.status" 
            placeholder="请选择状态" 
            clearable
          >
            <el-option label="有效" value="1" />
            <el-option label="无效" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listInteraction, 
  getInteraction, 
  delInteraction, 
  addInteraction, 
  updateInteraction 
} from "@/api/system/ainteraction"

export default {
  name: "Interaction",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生课堂互动记录表格数据
      interactionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        courseId: null,
        courseName: null,
        interactionType: null,
        interactionContent: null,
        interactionTime: null,
        scoreRewarded: null,
        status: null,
      },
      // 表单参数
      form: {
        id: null,
        userId: null,
        courseId: null,
        courseName: null,
        interactionType: null,
        interactionContent: null,
        interactionTime: null,
        scoreRewarded: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      // 表单校验规则（完善必填项校验）
      rules: {
        userId: [
          { required: true, message: "学号不能为空", trigger: ["blur", "change"] }
        ],
        courseId: [
          { required: true, message: "课程ID不能为空", trigger: ["blur", "change"] }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: ["blur", "change"] }
        ],
        interactionType: [
          { required: true, message: "互动类型不能为空", trigger: ["blur", "change"] }
        ],
        interactionContent: [
          { required: true, message: "互动内容不能为空", trigger: ["blur", "change"] }
        ],
        interactionTime: [
          { required: true, message: "互动时间不能为空", trigger: ["blur", "change"] }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: ["blur", "change"] }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询学生课堂互动记录列表 */
    getList() {
      this.loading = true
      listInteraction(this.queryParams).then(response => {
        this.interactionList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$modal.msgError("查询失败，请稍后重试")
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        courseId: null,
        courseName: null,
        interactionType: null,
        interactionContent: null,
        interactionTime: null,
        scoreRewarded: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加学生课堂互动记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      if (!id) {
        this.$modal.msgWarning("请选择一条数据进行修改")
        return
      }
      getInteraction(id).then(response => {
        this.form = response.data
        // 处理数字类型回显（确保下拉框能正确匹配）
        this.form.interactionType = this.form.interactionType + ""
        this.form.status = this.form.status + ""
        this.open = true
        this.title = "修改学生课堂互动记录"
      }).catch(() => {
        this.$modal.msgError("获取数据失败，请稍后重试")
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换为数字类型（与后端实体类Long类型匹配）
          this.form.interactionType = Number(this.form.interactionType)
          this.form.status = Number(this.form.status)
          this.form.scoreRewarded = Number(this.form.scoreRewarded)
          this.form.userId = Number(this.form.userId)
          this.form.courseId = Number(this.form.courseId)

          const request = this.form.id ? updateInteraction : addInteraction
          request(this.form).then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          }).catch(() => {
            this.$modal.msgError(this.form.id ? "修改失败" : "新增失败")
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids
      if (ids.length === 0) {
        this.$modal.msgWarning("请选择至少一条数据进行删除")
        return
      }
      this.$modal.confirm(`是否确认删除选中的 ${ids.length} 条学生课堂互动记录？`).then(() => {
        return delInteraction(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/interaction/export', {
        ...this.queryParams
      }, `interaction_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 优化表格和表单样式 */
::v-deep .el-table th {
  background-color: #f5f7fa !important;
}
::v-deep .el-dialog__body {
  padding: 20px !important;
}
::v-deep .el-form-item {
  margin-bottom: 15px !important;
}
</style>